﻿/* 
 * Since 2008 - 2012
 */
package com.hh.bss.customer.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;

import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.base.BaseSpringController;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.page.Page;
import com.hh.bss.common.page.PageRequest;
import com.hh.bss.common.tree.BranchCompanyTreeNode;
import com.hh.bss.common.tree.CompanyCvTreeNode;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.customer.entity.CompanyCv;
import com.hh.bss.customer.entity.Customer;
import com.hh.bss.customer.service.CompanyService;
import com.hh.bss.customer.service.CustomerService;
import com.hh.bss.customer.vo.query.CompanyQuery;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.entity.CvContactDetail;
import com.hh.bss.talent.entity.CvSalary;
import com.hh.bss.talent.vo.query.CvQuery;
import com.hh.bss.util.BeanUtils;
import com.hh.bss.util.ObjectUtils;
import com.hh.bss.util.StringHelper;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.JsonHelper;
import com.hh.bss.util.extjs.ListRange;

@Controller
public class CompanyController extends BaseSpringController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	private CompanyService companyService;
	private CustomerService customerService;

	private Company company;
	java.lang.Integer id = null;
	private String[] items;

	private static final ObjectMapper objectMapper = new ObjectMapper();

	/** 通过spring自动注入 */
	public void setCompanyServiceImpl(CompanyService service) {
		this.companyService = service;
	}

	/** 通过spring自动注入 */
	public void setCustomerServiceImpl(CustomerService service) {
		this.customerService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/**
	 * ExtGrid使用 列表
	 * 
	 * @throws IOException
	 */
	public void list(HttpServletRequest request, HttpServletResponse response, CompanyQuery companyQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyService.findPage(companyQuery);

		List<Company> Companylist = (List) page.getResult();
		ListRange<Company> resultList = new ListRange<Company>();
		resultList.setRows(Companylist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}
	
	public String managerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/companyManagerPage.jsp";	
	}
	public String info(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/customer/company/companyInfo.jsp";	
	}
	public String companyAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/customer/company/companyInfo.jsp";	
	}
	public String companyEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/customer/company/companyDetail.jsp";	
	}
	public String orgManager(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/customer/company/companyOrg.jsp";	
	}
	public String selectCompanyPage(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/customer/company/selectCompanyPage.jsp";	
	}

	/**
	 * ExtGrid使用 列表
	 * 
	 * @throws IOException
	 */
	public void listprojectcompany(HttpServletRequest request, HttpServletResponse response, CompanyQuery companyQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyService.findPage(companyQuery);

		List<Company> Companylist = (List) page.getResult();
		ListRange<Company> resultList = new ListRange<Company>();
		resultList.setRows(Companylist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void companycontext(HttpServletRequest request, HttpServletResponse response, CompanyQuery companyQuery) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map m = companyService.getCompanyContext(companyQuery.getId());

			if (m != null)
				result.put("data", m);
			result.put("success", true);
			result.put("msg", "成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid保存
	 * 
	 * @throws IOException
	 */
	public void save(HttpServletRequest request, HttpServletResponse response, Company company) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(Company.class, "creator")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(company, "creator", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(Company.class, "createDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(company, "createDt", new Date());
				} catch (Exception ex) {
				}
			}

			companyService.save(company);
			result.put("success", true);
			result.put("id", company.getId());
			result.put("msg", "添加成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void savecompanycv(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();

		Cv cv = new Cv();

		CvSalary cvSalary = new CvSalary();
		CompanyCv companyCv = new CompanyCv();
		String contact_json = request.getParameter("contact_data").toString(); // 联系信息
		List<CvContactDetail> contact_list = objectMapper.readValue(contact_json, new TypeReference<List<CvContactDetail>>() {
		});
		// List contacts=new ArrayList();
		try {

			// String cvId=request.getParameter("cvId");
			String companyId = request.getParameter("companyId");

			bind(request, cv);
			bind(request, cvSalary);

			if (!StringHelper.isEmpty(companyId))
				companyCv.setCompanyId(StringHelper.parseInteger(companyId, 0));
			// 判断人选是否增加过

			// 设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null) {

					cv.setNameInformer(onlineUser.getUsername());
					cv.setNameDt(new Date());
					// cv.setResumeInformer(onlineUser.getUsername());
					// cv.setResumeDt(new Date());
					if (StringHelper.isEmpty(cv.getNameInformer())) {
						cv.setNameInformer(cv.getCreator());
					}
					cv.setCreator(onlineUser.getUsername());
					cv.setCreateDt(new Date());

					if (cv.getNameDt() == null) {
						cv.setNameDt(cv.getCreateDt());
					}
					if (cv.getResumeDt() == null) {
						cv.setNameDt(cv.getCreateDt());
					}

					cv.setCvFrom(ConstantDic.CvFrom_H);
				}
			}

			// if(searchProjectCcList.getCcResult()!=null&&(searchProjectCcList.getCcResult()
			// == 2|| searchProjectCcList.getCcResult() == 3)){

			/*
			 * if(!StringHelper.isEmpty(cv.getCvName())){
			 * //if(!(cvService.checkUser(cv))){
			 * if(!(searchProjectCcListService.addCcCheck(cv, contact_list,
			 * searchProjectCcList))){
			 * searchProjectCcListService.saveCcCv(searchProjectCcList
			 * ,searchProjectCv,cv,cvSalary,contact_list); result.put("success",
			 * true); result.put("msg", "添加成功!"); }else{ result.put("failure",
			 * true); result.put("msg", "该人选资料已经存在!"); } }else{
			 * searchProjectCcListService
			 * .saveCcCv(searchProjectCcList,searchProjectCv
			 * ,cv,cvSalary,contact_list); result.put("success", true);
			 * result.put("msg", "添加成功!"); }
			 */
			// }
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid修改
	 * 
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response, Company company) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Company oldcompany = (Company) companyService.getById(company.getId());

			bind(request, oldcompany);
			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(Company.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldcompany, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(Company.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldcompany, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			companyService.update(oldcompany);
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * 公司信息批量修改
	 */
	public void batchupdate(HttpServletRequest request, HttpServletResponse response, Company company) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		String companyIds = request.getParameter("companyIds");
		if (companyIds != null && companyIds.length() > 0) {
			try {
				OnlineManager onlineManager = super.getOnlineManager(request, response);
				OnlineUser onlineUser = null;
				if (onlineManager != null) {
					onlineUser = onlineManager.getOnlineUser();
				}
				String[] companyIdArr = companyIds.split(",");
				for (String companyId : companyIdArr) {
					Company oldcompany = (Company) companyService.getById(Integer.parseInt(companyId));
					if (company.getIndustry() != null) { // 行业
						oldcompany.setIndustry(company.getIndustry());
					}
					if (company.getProperty() != null) { // 性质
						oldcompany.setProperty(company.getProperty());
					}

					if (company.getType() != null) { // 机构类型
						oldcompany.setType(company.getType());
					}

					if (company.getSize() != null) { // 人员规模
						oldcompany.setSize(company.getSize());
					}
					if (company.getLocation() != null) { // 城市
						oldcompany.setLocation(company.getLocation());
					}
					if (StringUtils.isNotEmpty(company.getIntegrity())) { // 信息完整度
						oldcompany.setIntegrity(company.getIntegrity());
					}
					if (StringUtils.isNotEmpty(company.getWebsite())) { // 网站
						oldcompany.setWebsite(company.getWebsite());
					}
					if (StringUtils.isNotEmpty(company.getTel())) { // 电话总机
						oldcompany.setTel(company.getTel());
					}
					if (StringUtils.isNotEmpty(company.getProfile())) { // 公司介绍
																		// 内部使用
						oldcompany.setProfile(company.getProfile());
					}
					if (StringUtils.isNotEmpty(company.getJobProfile())) { // 公司介绍
																			// 外部使用
																			// jobProfile
						oldcompany.setJobProfile(company.getJobProfile());
					}
					// bind(request,oldcompany);
					if (onlineUser != null && BeanUtils.isExistsProperty(Company.class, "modifier")) {
						try {
							BeanUtils.setProperty(oldcompany, "modifier", onlineUser.getUsername());
						} catch (Exception ex) {
						}
					}
					if (BeanUtils.isExistsProperty(Company.class, "modifiedDt")) {
						try {
							BeanUtils.setProperty(oldcompany, "modifiedDt", new Date());
						} catch (Exception ex) {
						}
					}
					companyService.update(oldcompany);
				}
				result.put("success", true);
				result.put("msg", "修改成功!");

			} catch (Exception e) {
				result.put("failure", true);
				result.put("msg", e.getMessage());
				e.printStackTrace();
			}

		} else {
			result.put("failure", true);
			result.put("msg", "公司ID不能为空.");
		}

		outJson(response, result);

	}

	/**
	 * extGrid删除
	 * 
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			for (int i = 0; i < idarray.length; i++) {
				java.lang.Integer id = new java.lang.Integer((String) idarray[i]);
				companyService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void get(HttpServletRequest request, HttpServletResponse response, Company company) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Company oldcompany = (Company) companyService.getById(company.getId());

			if (oldcompany != null)
				result.put("data", oldcompany);
			result.put("success", true);
			result.put("msg", "成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void companyorg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String companyId = request.getParameter("companyId");
		String deptId = request.getParameter("deptId");

		// Object[] os={StringHelper.parseInteger(companyId, 0)};
		List nodeLists = companyService.getOrg(StringHelper.parseInteger(companyId, 0), StringHelper.parseInteger(deptId, 0));
		Company company=(Company)companyService.getById(StringHelper.parseInteger(companyId, 0));

		BranchCompanyTreeNode companyTreeNode=new BranchCompanyTreeNode();
		
		companyTreeNode.setCompanyId(ObjectUtils.toString(company.getId()));
		companyTreeNode.setText(company.getAbbrName());
		companyTreeNode.setChildren(nodeLists);
		companyTreeNode.setId("rootNode");
		List rootList=new ArrayList();
		rootList.add(companyTreeNode);
		//JsonHelper.outJsonArray(response, nodeLists);
		JsonHelper.outJsonArray(response, rootList);
	}

	public void companyorgtreesave(HttpServletRequest request, HttpServletResponse response) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		String companyId = request.getParameter("companyId");
		String companyOrgTree = request.getParameter("companyOrgTree");
		// List<CvContactDetail> contact_list = objectMapper.readValue(
		// companyOrgTree, new TypeReference<List<CompanyCvTreeNode>>(){});
		// System.out.println(contact_list);
		try {

			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			com.hh.bss.auth.client.OnlineUser onlineUser = null;
			if (onlineManager != null)
				onlineUser = onlineManager.getOnlineUser();
			Map classMap = new HashMap();
			classMap.put("children", CompanyCvTreeNode.class);
			CompanyCvTreeNode root = (CompanyCvTreeNode) JSONObject.toBean(JSONObject.fromObject(companyOrgTree), CompanyCvTreeNode.class, classMap);
			companyService.saveOrgTree(onlineUser, StringHelper.parseInteger(companyId, 0), root);

			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		outJson(response, result);
	}

	public void customerorgonly(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String custId = request.getParameter("custId");
		String deptId = request.getParameter("deptId");

		Integer companyId = new Integer(0);
		Customer customer = (Customer) customerService.getById(StringHelper.parseInteger(custId, 0));
		if (customer != null)
			companyId = customer.getCompanyId();
		// Object[] os={StringHelper.parseInteger(companyId, 0)};
		List nodeLists = companyService.getOrgOnly(companyId, StringHelper.parseInteger(deptId, 0));
		JsonHelper.outJsonArray(response, nodeLists);
	}

	public void companyorgonly(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String companyId = request.getParameter("companyId");
		String deptId = request.getParameter("deptId");

		// Object[] os={StringHelper.parseInteger(companyId, 0)};
		List nodeLists = companyService.getOrgOnly(StringHelper.parseInteger(companyId, 0), StringHelper.parseInteger(deptId, 0));
		JsonHelper.outJsonArray(response, nodeLists);
	}

	public void CheckCompany(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 检查公司是否重复
		Map<String, Object> result = new HashMap<String, Object>();
		String abbrName = request.getParameter("abbrName");
		String address = request.getParameter("address");
		String tel = request.getParameter("tel");

		Company company = new Company();
		// if(StringUtils.isNotEmpty(abbrName)){
		company.setAbbrName(abbrName);
		// }
		// if(StringUtils.isNotEmpty(tel)){
		company.setTel(tel);
		// }
		// if(StringUtils.isNotEmpty(address)){
		company.setAddress(address);
		// }

		// boo
		result.put("success", !companyService.isCompanyRepeat(company));
		// Object[] os={StringHelper.parseInteger(companyId, 0)};
		JsonHelper.outJsonArray(response, result);
	}

	/**
	 * 从excel 导入公司信息
	 * 
	 * @param request
	 * @param response
	 * @param company
	 * @throws IOException
	 */
	public void importcompany(HttpServletRequest request, HttpServletResponse response, Company company) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 设置创建用户和创建时间
			OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && BeanUtils.isExistsProperty(Company.class, "creator")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(company, "creator", "waki.hu");
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}

			if (BeanUtils.isExistsProperty(Company.class, "createDt")) {
				try {
					BeanUtils.setProperty(company, "createDt", new Date());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			companyService.importCompanyFromExcel("C:\\公司录入模板20130130.xls");
			result.put("success", true);
			result.put("msg", "添加成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void deletelist(HttpServletRequest request, HttpServletResponse response, CompanyQuery companyQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyService.findDelPage(companyQuery);

		List<Company> Companylist = (List) page.getResult();
		ListRange<Company> resultList = new ListRange<Company>();
		resultList.setRows(Companylist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void mergelist(HttpServletRequest request, HttpServletResponse response, CompanyQuery companyQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyService.findCompanyMergePage(companyQuery);

		List<Company> list = (List) page.getResult();
		ListRange<Company> resultList = new ListRange<Company>();
		resultList.setRows(list);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void merge(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		String ids = request.getParameter("ids");
		if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(ids)) {
			if (ids.contains(id)) {
				ids = ids.replace(id, "");
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			companyService.companyMerger(id, ids);
			result.put("success", true);
			result.put("msg", "合并成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * 处理简历
	 * 
	 * @param request
	 * @param response
	 * @param cv
	 */
	public void solved(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineManager onlineManager = new OnlineManager(request, response);
			OnlineUser onlineUser = onlineManager.getOnlineUser();
			String ids = request.getParameter("ids");
			String integrity = request.getParameter("integrity");
			String[] idArray = ids.split(",");
			for (String id : idArray) {
				Company company = (Company) this.companyService.getById(Integer.valueOf(id));
				company.setIntegrity(integrity);
				company.setModifier(onlineUser.getUsername());
				company.setModifiedDt(new Date());
				this.companyService.update(company);
			}
		} catch (NumberFormatException e) {
			result.put("failure", true);
			result.put("msg", "数字格式有误");
			e.printStackTrace();
		} catch (DataAccessException e) {
			result.put("failure", true);
			result.put("msg", "数据访问异常,请联系管理员");
			e.printStackTrace();
		}
		result.put("success", true);
		result.put("msg", "修改成功!");
		outJson(response, result);

	}

	public void sameofdellist(HttpServletRequest request, HttpServletResponse response, CompanyQuery companyQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyService.findSameOfDelCvPage(companyQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void recover(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		companyService.recoverCompany(ids);
		result.put("success", true);
		result.put("msg", "恢复成功!");
		outJson(response, result);

	}

}
